package com.zhidao.backend.service.Impl;

import com.aliyun.oss.OSSClient;
import com.zhidao.backend.service.IOssService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 对象存储服务实现
 */
@Service
public class OssServiceImpl implements IOssService {

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;

    private OSSClient ossClient;

    @Autowired
    public void setOssClient(OSSClient ossClient) {
        this.ossClient = ossClient;
    }

    @Override
    public String uploadImage(@NotNull MultipartFile file) {
        try {
            return upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String upload(InputStream inputStream, String name) {
        String objectName = getObjectName(name);
        ossClient.putObject(bucketName, objectName, inputStream);
        return formatURL(objectName);
    }

    public String getObjectName(@NotNull String name) {
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = localDate.format(dateTimeFormatter);
        String fileName = UUID.randomUUID().toString();
        String fileExtension = name.substring(name.lastIndexOf("."));
        return dirPrefix + folder + "/" + fileName + fileExtension;
    }

    public String formatURL(String name) {
        return "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + name;
    }
}
